<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item prop="query">
        <el-input v-model="queryParams.query" placeholder="请输入打印机编号（SN码）/公开码/打印机名称" clearable @keyup.enter="handleQuery"
          style="width: 350px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" size="small" icon="Download" @click="handleExport"
          v-hasPermi="['manage:printer:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" size="small" icon="pointer" @click="handleSync"
          v-hasPermi="['manage:printer:sync']">同步</el-button>
      </el-col>
	  <el-col :span="1.5">
		<el-popconfirm title="确定要解绑吗？" @confirm="()=>{offBindPrint('zb')}">
			<template #reference>
				<el-button type="danger" size="small" icon="pointer" :disabled="multiple"
				v-hasPermi="['manage:printer:bindZB']">解绑总部</el-button>
			</template>
		</el-popconfirm>
        
      </el-col>
	  <el-col :span="1.5">
		<el-popconfirm title="确定要解绑吗？" @confirm="()=>{offBindPrint('md')}">
			<template #reference>
				<el-button type="danger" size="small" icon="pointer" :disabled="multiple"
          v-hasPermi="['manage:printer:bindMD']">解绑门店</el-button>
			</template>
		</el-popconfirm>
        
      </el-col>
	  <el-col :span="1.5">
        <el-button type="primary" size="small" icon="pointer" :disabled="multiple" @click="()=>{openBindPrint('zb')}"
          v-hasPermi="['manage:printer:bindZB']">绑定总部</el-button>
      </el-col>
	  <!-- <el-col :span="1.5">
        <el-button type="primary" size="small" icon="pointer" :disabled="multiple" @click="()=>{openBindPrint('md')}"
          v-hasPermi="['manage:printer:bindMD']">绑定门店</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border flexible v-loading="loading" :data="printerList" @selection-change="handleSelectionChange" @row-click="(row)=>{console.log(row)}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center"/>
      <el-table-column label="打印机编号" align="center" prop="printerKey" width="150"/>
      <!-- <el-table-column label="公开码" align="center" prop="publicCode" /> -->
      <el-table-column label="打印机名称" align="center" prop="printerName" width="150"/>
      <el-table-column label="总部名称" align="center" prop="headquartersName" width="180">
		<template #default="scope">
			<span>{{scope.row.headquartersName}}</span>

			<el-popconfirm title="确定要解绑吗？" @confirm="()=>{offBindPrint('zb', scope.row.printerKey)}" v-if="scope.row.storeName">
				<template #reference>
					<el-button type="danger" size="small" v-if="scope.row.headquartersName" v-hasPermi="['manage:printer:bindZB']"> 解绑 </el-button>

				</template>
			</el-popconfirm>
			<el-button type="primary" size="small" v-else  @click="()=>{openBindPrint('zb', scope.row.printerKey)}" v-hasPermi="['manage:printer:bindZB']"> 绑定 </el-button>
		</template>
	  </el-table-column>
      <el-table-column label="门店名称" align="center" prop="storeName" width="180">
		<template #default="scope">
			<span>{{scope.row.storeName}}</span>
			<el-popconfirm title="确定要解绑吗？" @confirm="()=>{offBindPrint('md', scope.row.printerKey)}" v-if="scope.row.storeName">
				<template #reference>
				<el-button type="danger" size="small" v-hasPermi="['manage:printer:bindMD']"> 解绑 </el-button>

				</template>
			</el-popconfirm>
			<el-button type="primary" size="small" v-else @click="()=>{openBindPrint('md', scope.row.printerKey)}" v-hasPermi="['manage:printer:bindMD']"> 绑定 </el-button>
		</template>
		</el-table-column>
	  <el-table-column label="状态" align="center" prop="printerStatus" width="100">
		<template #default="scope">
			<span :class="scope.row.printerStatus === '1' ? 'color-#1acf68':'color-gray'">{{scope.row.printerStatus === '1' ? '在线 正常' :'离线' }}</span>
		</template>
		</el-table-column>
      <el-table-column label="语音" align="center" prop="soundType" >
		<template #default="scope">
			<span>{{soundTypeList[scope.row.soundType]}}</span>
		</template>
		</el-table-column>
      <el-table-column label="声音大小" align="center" prop="soundSize" >
		<template #default="scope">
			<span>{{soundSizeList[scope.row.soundSize]}}</span>
		</template>
	  </el-table-column>
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="manage_printer_status" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="固件版本" align="center" prop="version" /> -->
      <el-table-column label="添加时间" align="center" prop="createTime" width="180"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:printer:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />


    <!-- 修改打印机对话框 -->
    <el-dialog :title="title" v-model="openModify" width="550px" append-to-body>
      <el-form ref="printerRef" :model="form" :rules="rules" label-width="120px">
		<el-form-item label="打印机名称" prop="printerName">
          <el-input v-model="form.printerName" disabled placeholder="请输入打印机编号" />
        </el-form-item>
        <el-form-item label="打印机编号" prop="printerKey">
          <el-input v-model="form.printerKey" disabled placeholder="请输入打印机编号" />
        </el-form-item>

        <el-form-item label="语音设置:" prop="soundType" label-width="120px">
          <el-select v-model="form.soundType" placeholder="请选择来单语音:" clearable class="w-full">
            <el-option v-for="dict in manage_printer_voiceType" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="音量设置:" prop="soundSize" label-width="120px">
          <el-select v-model="form.soundSize" placeholder="请选择打印机音量:" clearable class="w-full">
            <el-option v-for="dict in manage_printer_volumeLevel" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="绑定总部:" prop="headquartersId" label-width="120px">
          <el-select v-model="form.headquartersId" placeholder="请选择绑定的总部:" clearable class="w-full">
            <el-option v-for="dict in headquartersList" :key="dict.storeId" :label="dict.storeName"
              :value="dict.storeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定门店:" prop="storeId" label-width="120px">
          <el-select v-model="form.storeId" placeholder="请选择绑定的门店:" clearable class="w-full">
            <el-option v-for="dict in storeList" :key="dict.storeId" :label="dict.storeName"
              :value="dict.storeId" />
          </el-select>
        </el-form-item> -->

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="modifyVoice">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
	<!-- 绑定打印机对话框 -->
    <el-dialog title="绑定打印机" v-model="openBind" width="550px" append-to-body>
		<el-select
			v-model="bindStoreVal"
			clearable
			placeholder="请选择对应门店"
			filterable
		>
			<el-option v-for="dict in showStoreList" :key="dict.storeId" :label="dict.storeName"
              :value="dict.storeId" />
		</el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="configBind(storeLabel)">确 定</el-button>
          <el-button @click="cancelBind">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Printer" lang="ts">
import { addPrinters, deletePinter, getPrinterById, getPrinterData, getPrinterList, setVoiceType, syncPinter, updatePrinter, unbindPrint, zbBindPrint, mdBindPrint, bindPrint } from '@/api/manage/printer';
import { ElForm, ElMessage } from 'element-plus';
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import usePinter from '@/api/request/manage/pinter/index';
import { easyListStore, listStore } from '@/api/system/store';

const { proxy } = getCurrentInstance() as any;

const printerList = ref([]);
const open = ref(false);
const openModify = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
// const headquartersList = ref<any[]>([]);
// const storeList = ref<any[]>([]);
const soundTypeList = ref({'0':'真人语音','3':'嘀嘀声','4':'静音'}) ;
const soundSizeList =ref({ '0':'大','1':'中','2':'小','3':'关闭'}) ;
const { manage_printer_status } = proxy.useDict('manage_printer_status');
const { manage_printer_voiceType } = proxy.useDict('manage_printer_voiceType');
const { manage_printer_volumeLevel } = proxy.useDict('manage_printer_volumeLevel');


const data = reactive({
	form: {} as any,
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		query: ''
	},
	rules: {
		printerKey: [
			{ required: true, message: '请输入打印机编号', trigger: 'blur' },
		],
		printerName: [
			{ required: true, message: '请输入打印机名称', trigger: 'blur' },
		],
		soundType: [
			{ required: true, message: '请输入打印机声音类型', trigger: 'blur' },
		],
		soundSize: [
			{ required: true, message: '请输入打印机声音大小', trigger: 'blur' },
		],
	}
});
const queryRef = ref<InstanceType<typeof ElForm>>();
const { queryParams, form, rules } = toRefs(data);

const { handlePrinter } = usePinter();

/** 查询打印机列表 */
async function getList() {
	loading.value = true;
	const res = await getPrinterData(queryParams.value);
	// let voiceList = {'0':}
	// printerList.value = res.data.list;
	// const soundTypeList = {'0':'真人语音','3':'嘀嘀声','4':'静音'};
	// const soundSizeList ={ '0':'大','1':'中','2':'小','3':'关闭'};
	// printerList.value = res.data.list.map((ele:any)=>{
	// 	return {
	// 		...ele,
	// 		soundType:soundTypeList[ele.soundType],
	// 		soundSize:soundSizeList[ele.soundSize],
	// 	};
	// });
	printerList.value = res.data.list;
	total.value = res.data.total;
	loading.value = false;
}
/**
 * 解除绑定打印机
 * @param store {String} zb md，总部 / 门店
 * @param print {Array} 打印机数组
 */
async function offBindPrint(store:'zb' | 'md', print?:any){
	try {
		const res = await unbindPrint({ids:print ? [print] : ids.value,bj:store});
		getList();
		ElMessage.success('解绑成功');
	} catch (error) {
		ElMessage.error('解绑失败');
		
	}
}

const bindPrintIds = ref<string[]>([]); // 绑定的打印机id
const openBind = ref(false); // 绑定弹窗
const bindStoreVal = ref(''); // 绑定的门店id
const showStoreList = ref<any>([]); // 绑定的门店id
const storeLabel = ref<'zb'|'md'>('zb');
/**
 * 打开绑定打印机
 * @param store {String} zb md
 * @param print {Array} 打印机数组
 */
async function openBindPrint(store:'zb' | 'md', print?:any){
	openBind.value = true;
	const storeRes = await easyListStore({storeLb:store === 'zb' ? '1' : '2'});
	showStoreList.value = storeRes.data;
	bindPrintIds.value = print ? [print] : ids.value;
	storeLabel.value = store;
}

// 取消按钮
function cancel() {
	open.value = false;
	openModify.value = false;
	reset();
}

// 取消绑定按钮
function cancelBind() {
	openBind.value = false;
	bindStoreVal.value = '';
	bindPrintIds.value = [];
	storeLabel.value = 'zb';

}
// 确定绑定按钮
async function configBind(store:'zb' | 'md') {
	// if(store === 'zb'){
	// 	zbBindPrint({headquartersId:bindStoreVal.value,
	// 		printerKey:bindPrintIds.value
	// 	});
	// 	bindPrint()
	// }else{
	// 	mdBindPrint({StoreId:bindStoreVal.value,
	// 		printerKey:bindPrintIds.value
	// 	});
	// }
	// bindPrint()
	// cancelBind();
	try {
		const res = await bindPrint({ids:bindPrintIds.value,storeId:bindStoreVal.value,bj:store});
		ElMessage.success('绑定成功');
	} catch (error) {
		ElMessage.error('绑定失败');
	}
	cancelBind();
	getList();
}

// 表单重置
function reset() {
	form.value = {
		id: null, 
		printerName: '',
		soundSize:'',
		soundType:'', 
		headquartersId:'', 
		storeId:'', 
	};
	proxy.resetForm('printerRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm(queryRef);
	handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: { map: (arg0: (item: any) => any) => never[]; length: number; }) {
	ids.value = selection.map((item: { printerKey: string; }) => item.printerKey);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
	console.log(ids.value, single.value, multiple.value);
}

/** 新增按钮操作 */
async function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加打印机';
}

/** 修改按钮操作 */
async function handleUpdate(row: any) {
	reset();
	// const printer = await getPrinterById(row.id);
	// form.value = printer.data;
	form.value = {...row};
	console.log(form.value);
	openModify.value = true;
	title.value = '修改打印机';
}
/** 查询门店下拉树结构 */
// const getStoreList = async () => {
// 	const storeRes = await listStore({});
// 	headquartersList.value = storeRes.data.filter((ele:any)=>ele.storeLb === '1');
// 	storeList.value = storeRes.data.filter((ele:any)=>ele.storeLb === '2');
// 	console.log(headquartersList,storeList);
// };

/** 提交按钮 */
function submitForm() {
	proxy.$refs['printerRef'].validate(async (valid: any) => {
		if (valid) {
			const params = { items: [{ ...form.value }] };
			try {
				const res: any = await addPrinters(params);
				if (res.fail.length > 0) {
					ElMessage.error('新增打印机失败');
				}
				if (res.success.length > 0) {
					proxy.$modal.msgSuccess('新增成功');
					open.value = false;

					getList();
				}
			} catch (error) {
				ElMessage.error('新增打印机失败');
			}
		}
	});
}
async function handleSync(){
	try {
		loading.value = true;
	  const res = await getPrinterList({page:1,limit:5000,query:''});
		const sizeList = {sylx5:'0',sylx6:'1',sylx7:'2',sylx8:'3'}; // 5:大 6:中 7:小 8:静音 声音大小
		const voiceList = {sylx0:'0',sylx3:'3',sylx4:'4',}; // 0:真人语音 3: 滴滴声  4:静音  声音类型
		console.log(res.data.rows,'----');
		// 		voiceType:"sylx4" volumnType:"sylx8"
		const syncData = res.data.rows.map((ele:any)=>({
			printerKey:ele.sn,
			printerName:ele.name,
			soundType:voiceList[ele.voiceType] || '0',
			soundSize:sizeList[ele.volumnType] || '0',
			createTime:ele.bindTime,
		}));
		await syncPinter({xqPrinters: syncData});
		ElMessage.success('同步成功！');
		loading.value = true;
		queryParams.value.pageNum = 1;
		getList();
	} catch (error) {
		ElMessage.error('同步失败，请检查网络');
	}
}
/**
 * 修改声音
 */
async function modifyVoice() {
	
	const params = {
		sn: form.value.printerKey,
		voiceType: form.value.soundType,
		volumeLevel: form.value.soundSize,
	};
	const typeRes = await setVoiceType(params);
	const printerRes = await updatePrinter({id:form.value.id,soundSize:form.value.soundSize,soundType:form.value.soundType});
	ElMessage.success('修改声音成功');
	getList();
	openModify.value = false;
}

/** 导出按钮操作 */
function handleExport() {
	proxy.download('manage/printer/exportByStream', {
		...queryParams.value
	}, `printer_${new Date().getTime()}.xlsx`);
}



getList();
// getStoreList();
</script>